/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package alarmlistener;

import alarmlistener.elements.Input;
import alarmlistener.logger.InputLogger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author rbs
 */
public class ListeningServerThread extends Thread{

    private BackgroundServer server;
    private ArrayList<String> rics = new ArrayList<String>();
    private ArrayList<String> texts = new ArrayList<String>();
    private ArrayList<String> funcs = new ArrayList<String>();
    private String express;
    private SchleifenManager mgr;
    private Boolean relAlert;
    private Logger log;
    private Timer timer;
    private ResetTimer res;
    
    public ListeningServerThread(String abbruchRIC, SchleifenManager ricmgr) throws IOException, InterruptedException {
        express = abbruchRIC;
        server = new BackgroundServer();
        mgr = ricmgr;
        timer = new Timer();
    }

    public void run() {

        log = Logger.getLogger(this.getClass().getName());
        relAlert = false;
        try {
            while(true)
            {
                System.out.println("restarting from begin...");
                while(rics.isEmpty() || !(rics.get(rics.size() -1 ).equals(express) && relAlert))
                {
                    server.conNewClient();
                    log.log(Level.INFO, "Client verbunden.");
                    String input = server.readLine();
                    //System.out.println(input);
                    if (input.equals("CON FWDISP SERVER")) {
                        server.sendLine("CON OK");
                        log.log(Level.INFO, "Connection sucessfully established");

                        String ric = null;
                        String func = null;
                        String txt = null;
                        try {
                            ric = server.readLine();
                            func = server.readLine();
                            txt = server.readLine();
                            log.log(Level.FINER, "Client sendet: ric = {0} func = {1} txt= {2}", new Object[]{ric, func, txt});
                        } catch (Exception e) {
                            log.log(Level.SEVERE, "Could not read from client:" + e);
                        }
                        
                        if (mgr.isRelevant(ric))
                        {
                            log.log(Level.FINE, "RIC ist relevant.");
                            if (!ric.equals(express))
                            {
                                if(res != null)
                                    res.cancel();
                                
                                relAlert = true;
                                res = new ResetTimer(this);
                                timer.schedule(res, 3000);
                            }
                            getRics().add(ric);
                            getFuncs().add(func);
                            getTexts().add(txt);
                            InputLogger.getInstance().addInput(new Input(ric, func, txt, true));
                        }
                        else
                            InputLogger.getInstance().addInput(new Input(ric, func, txt, false));
                        
                    } else {
                        log.log(Level.SEVERE, "Fehler bei Netzwerkverbindung!");
                        System.out.println("Error while connecting");
                    }
                }
                analyseAndShow();
            }

        } catch (IOException ex) {
            Logger.getLogger(ListeningServerThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    public void analyseAndShow()
    {
        try {
            
            log.log(Level.INFO, "Analysiere empfangene Daten...");
            DataAnalyser dataAnalyser = new DataAnalyser(getRics(), getTexts(), getFuncs(), mgr);
            InputLogger.getInstance().addSpecialInput("Display wird gestartet");
            String fWDispStartString = dataAnalyser.getFWDispStartString();
            String expressText = dataAnalyser.getExpressText();
            
            System.out.println("java -jar FWDisp.jar --fmslaunch" + " \"" + expressText + "\" " + fWDispStartString);
            log.log(Level.FINE,"StartString for FWDisp:\njava -jar FWDisp.jar --fmslaunch" + " \"" + expressText + "\" " + fWDispStartString);
            //JOptionPane.showMessageDialog(null, "java -jar FWDisp.jar --fmslaunch" + " \"" + dataAnalyser.getExpressText() + "\" " + dataAnalyser.getFWDispStartString());
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("java -jar FWDisp.jar --fmslaunch" + ' ' + '\"' + expressText + '\"' + ' ' + fWDispStartString);
            
            reset();
        } catch (IOException ex) {
            Logger.getLogger(ListeningServerThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void reset()
    {
        rics = new ArrayList<String>();
        texts = new ArrayList<String>();
        funcs = new ArrayList<String>();
        relAlert = false;
        log.log(Level.INFO, "resetted Rics...");
    }

    /**
     * @return the rics
     */
    public ArrayList<String> getRics() {
        return rics;
    }

    /**
     * @return the texts
     */
    public ArrayList<String> getTexts() {
        return texts;
    }

    /**
     * @return the funcs
     */
    public ArrayList<String> getFuncs() {
        return funcs;
    }

}
